package com.dianxin.smartpark.web.config;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.exception.NotPermissionException;
import com.chinatelecom.response.common.CommonResponseBody;
import com.chinatelecom.response.constant.ErrMsgEnum;
import com.chinatelecom.response.expception.AppSystemException;
import com.chinatelecom.response.utils.ResponseBodyWrapperUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

import javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.Set;
import java.util.stream.Collectors;

import static com.chinatelecom.response.constant.ErrMsgEnum.PLEASE_LOGIN;

/**
 * @author wangkai
 */
@ControllerAdvice
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 声明要捕获的异常
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public CommonResponseBody<Object> defaultExceptionHandler(HttpServletRequest request, Exception e) {
        logger.error("异常信息：",e);
        if (e instanceof AppSystemException || e instanceof IllegalArgumentException){
            return  ResponseBodyWrapperUtil.fail(e.getMessage(),"50000");
        }
        if (e instanceof ConstraintViolationException){

            ConstraintViolationException ex = (ConstraintViolationException) e;
            Set<ConstraintViolation<?>> constraintViolations = ex.getConstraintViolations();
            return ResponseBodyWrapperUtil.fail(constraintViolations.stream().map(ConstraintViolation::getMessage).collect(Collectors.toList()).toString(),"50000");
        }
        if (e instanceof NotLoginException){
           return ResponseBodyWrapperUtil.fail(PLEASE_LOGIN);
        }
        if (e instanceof NotPermissionException){
           return ResponseBodyWrapperUtil.fail(e.getMessage(),e.getMessage());
        }
        return ResponseBodyWrapperUtil.fail(ErrMsgEnum.SERVER_ERROR);
    }

}
